<template>
  <el-dialog
    :title="isEdit ? '编辑项目' : '新增项目'"
    v-model="dialogVisible"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="form.projectName"
          placeholder="请输入项目名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="项目描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入项目描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="项目状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择项目状态">
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已暂停" :value="2" />
          <el-option label="已完成" :value="3" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="项目进度" prop="progress">
        <el-slider
          v-model="form.progress"
          :min="0"
          :max="100"
          :step="5"
          show-input
          :format-tooltip="(val) => val + '%'"
        />
      </el-form-item>
      
      <el-form-item label="项目负责人" prop="leaderId">
        <el-select
          v-model="form.leaderId"
          placeholder="请选择项目负责人"
          filterable
          remote
          :remote-method="searchUsers"
          :loading="userLoading"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.realName"
            :value="user.id"
          >
            <span>{{ user.realName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ user.roleName }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="Git地址" prop="gitUrl">
        <el-input
          v-model="form.gitUrl"
          placeholder="请输入Git仓库地址"
        >
          <template #prepend>https://</template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="form.startDate"
          type="date"
          placeholder="选择开始日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="form.endDate"
          type="date"
          placeholder="选择结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  project: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const isEdit = computed(() => !!props.project)

const formRef = ref()
const submitting = ref(false)
const userLoading = ref(false)
const userOptions = ref([])

// 表单数据
const form = reactive({
  projectName: '',
  description: '',
  status: 0,
  progress: 0,
  leaderId: null,
  gitUrl: '',
  startDate: '',
  endDate: ''
})

// 表单验证规则
const rules = {
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 100, message: '项目名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '项目描述不能超过500个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ],
  progress: [
    { required: true, message: '请设置项目进度', trigger: 'change' }
  ],
  leaderId: [
    { required: true, message: '请选择项目负责人', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ]
}

// 监听项目数据变化，填充表单
watch(() => props.project, (newProject) => {
  if (newProject) {
    Object.assign(form, {
      projectName: newProject.projectName || '',
      description: newProject.description || '',
      status: newProject.status || 0,
      progress: newProject.progress || 0,
      leaderId: newProject.leaderId || null,
      gitUrl: newProject.gitUrl || '',
      startDate: newProject.startDate || '',
      endDate: newProject.endDate || ''
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 导入模拟用户数据
import { mockUsers } from '@/api/mockData'

// 搜索用户
const searchUsers = async (query) => {
  if (query) {
    try {
      userLoading.value = true
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 300))
      
      // 使用模拟数据进行搜索
      const filteredUsers = mockUsers.filter(user => 
        user.realName.toLowerCase().includes(query.toLowerCase()) ||
        user.username.toLowerCase().includes(query.toLowerCase())
      )
      userOptions.value = filteredUsers
    } catch (error) {
      console.error('搜索用户失败:', error)
      userOptions.value = []
    } finally {
      userLoading.value = false
    }
  } else {
    userOptions.value = mockUsers
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    projectName: '',
    description: '',
    status: 0,
    progress: 0,
    leaderId: null,
    gitUrl: '',
    startDate: '',
    endDate: ''
  })
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟成功响应
    const mockResult = {
      success: true,
      data: {
        id: isEdit.value ? props.project.id : Date.now(),
        ...form,
        projectName: form.projectName,
        description: form.description,
        status: form.status,
        progress: form.progress,
        leaderId: form.leaderId,
        gitUrl: form.gitUrl,
        startDate: form.startDate,
        endDate: form.endDate,
        createdAt: isEdit.value ? props.project.createdAt : new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    }
    
    if (mockResult.success) {
      ElMessage.success(isEdit.value ? '项目更新成功' : '项目创建成功')
      emit('success', mockResult.data)
      handleClose()
    } else {
      ElMessage.error(mockResult.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 组件挂载时加载用户列表
onMounted(() => {
  searchUsers('')
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-slider__input) {
  width: 80px;
}
</style>
